<?php

namespace globalunit\utils;

use globalunit\logic\UidNumbers;

class GenID
{

    public static function gen()
    {
        return sha1(uniqid('_' . mt_rand(1, 1000000) . getmypid(), true));
    }

    public static function uuid($prefix = "")
    {
        $chars = md5(uniqid(mt_rand() . getmypid(), true));
        $uuid = substr($chars, 0, 8) . '-'
            . substr($chars, 8, 4) . '-'
            . substr($chars, 12, 4) . '-'
            . substr($chars, 16, 4) . '-'
            . substr($chars, 20, 12);
        return $prefix . $uuid;
    }

    public static function genid($rediscli)
    {
        $SCRIPT = <<<crifan
                local v = redis.call('exists', KEYS[1])
                if v==1 then
                    return nil
                end
                redis.call('set',KEYS[1],KEYS[2])
                return KEYS[2]
crifan;
        while (true) {
            $r = mt_rand(111111, 999999);
            $k = $GLOBALS['GAMENAME'] . "-uid-" . $r;
            $args_args = array($k, $r);
            $a = $rediscli->eval($SCRIPT, $args_args, 2);
            if (isset($a)) {
                return $r;
            }
        }
    }
}
